package com.lateam2010.register.server;

import java.io.IOException;
import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.lateam2010.register.client.RegisterService;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public final class RegisterServiceImpl extends RemoteServiceServlet implements
		RegisterService {

	private static final PersistenceManagerFactory PMF = JDOHelper
			.getPersistenceManagerFactory("transactions-optional");

	public RegisterServiceImpl() {
	}
	
	private static void checkPassword(PersistenceManager pm, String password) throws PasswordException {
		List<Password> list = (List<Password>) pm.newQuery(Password.class, "password == '" + password + "'").execute();
		if (list.isEmpty()) {
			list = (List<Password>) pm.newQuery(Password.class).execute();
			if (!list.isEmpty()) {
				throw new PasswordException();
			}
		}
	}

	@Override
	public void register(String password, String email, String name)
			throws IOException {
		PersistenceManager pm = PMF.getPersistenceManager();
		try {
			checkPassword(pm, password);
			pm.makePersistent(new Address(email, name));
		} finally {
			pm.close();
		}
	}

	@Override
	public String[][] list(String password) throws IOException {
		return listAll(password);
	}
	
	public static String[][] listAll(String password) throws IOException {
		PersistenceManager pm = PMF.getPersistenceManager();
		try {
			checkPassword(pm, password);
			List<Address> all = (List<Address>) pm.newQuery(Address.class)
					.execute();
			String[][] a = new String[all.size()][];
			int i = 0;
			for (Address aa : all) {
				a[i++] = new String[] { aa.getEmail(), aa.getName() };
			}
			return a;
		} finally {
			pm.close();
		}
	}

	@Override
	public void delete(String password, String email) throws IOException {
		PersistenceManager pm = PMF.getPersistenceManager();
		try {
			checkPassword(pm, password);
			pm.newQuery(Address.class, "email == '" + email + "'")
					.deletePersistentAll();
		} finally {
			pm.close();
		}
	}
	
	@Override
	public void changePassword(String password, String newPassword)
			throws IOException {
		PersistenceManager pm = PMF.getPersistenceManager();
		try {
			checkPassword(pm, password);
			pm.newQuery(Password.class, "password == '" + password + "'")
					.deletePersistentAll();
			pm.makePersistent(new Password(newPassword));
		} finally {
			pm.close();
		}
	}
}
